<template>
  <div class="canvasCssSpirit">
      <canvas id="pic" ref="picRef" :width="rect?.width" :height="rect?.height"></canvas>
  </div>
</template>

<script lang="ts">
import { Vue, Options } from 'vue-property-decorator';
interface Pos{
  x: number,
  y: number
}

@Options({ components: {

} })
export default class CanvasCssSpirit extends Vue {
  public rect: DOMRect|null = null;
  public ctx: CanvasRenderingContext2D|null=null;
  private timer: number|null = null;
  public img= new Image();
  public index = 0;

  public draw() {
    this.img.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Ff5ee703a56424002b5c43d9598153fb2.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_Q1NETiBA6L-w5a6JYW4%3D%2Csize_21%2Ccolor_FFFFFF%2Ct_70%2Cg_se%2Cx_16%23pic_cente&refer=http%3A%2F%2Fimg-blog.csdnimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648634774&t=d97711b14d4eba6931547b0ccb367e51';
    this.img.onload = () => {
      // 箭头函数没有自己的this
      this.play();
    };
  }
  public play() {
    const i = Math.floor(this.index % 4);
    console.log(i);
    this.ctx!.drawImage(
      this.img, this.img.naturalWidth  * i / 4, 0, this.img.naturalWidth / 4, this.img.naturalHeight,
      0, 0, this.img.naturalWidth / 4, this.img.naturalHeight,
    );
    // void ctx.drawImage(image, dx, dy);
    // void ctx.drawImage(image, dx, dy, dWidth, dHeight);
    // void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
    // s开头的代表矩形裁剪框的参数 d开头的代表图片自身的参数
    this.index += 0.1;
    this.timer = window.requestAnimationFrame(this.play);
    if (this.index === 50) {
      window.cancelAnimationFrame(this.timer);
    }
  }
  public mounted() {
    this.rect = (this.$el as HTMLDivElement).getBoundingClientRect();
    this.ctx = (this.$refs.picRef as HTMLCanvasElement).getContext('2d');
    this.draw();
  }
};
</script>

<style lang="postcss">
.canvasCssSpirit{
  touch-action: none;
  position: relative;
  width: 100%;
  height: 100%;
  /* background-color: grey; */
 #pic{
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }

}
</style>
